<?php
 
include 'db.php'; //database config and connection
 
//the switch gets the variables from the url with the corresponding case
switch(isset($_GET['action'])) {
	//add item from url variable
    case "add_item":
        AddProduct($_GET["id"]);
        ShowCart();
        break;     
}
 
//function add product to cart
function AddProduct($itemId) {
    $id_session = session_id();
 
    $result = mysql_query("select count(*) from cart where sessionId = '" . $id_session . "' and itemId = $itemId");
    $row = mysql_fetch_row($result);
    $numRows = $row[0];
 
    if($numRows == 0) {
        //This item doesn't exist in the users cart,
        //we will add it with an insert query
        @mysql_query("insert into cart(sessionId, itemId, qty) values('" . $id_session . "', $itemId, 1)");
        header("Location: index.php");
    }
    else {
        //This item already exists in the users cart,
        //we will update it instead
        UpdateProduct($itemId);
    }
}
 
//function update product +1 if product is already in cart 
function UpdateProduct($itemId, $qty) {
    $id_session = session_id();
    @mysql_query("update cart set qty = qty + 1 where sessionId = '" . $id_session . "' and itemId = $itemId");
    header("Location: list.php");
}
 
//select current user shopping cart and get total
function ShowCart(){
    $id_session = session_id();
    $totalCost = 0;
 	
    $sql = "SELECT *
            FROM cart
            INNER JOIN items
            ON cart.itemId = items.itemId
            WHERE cart.sessionId = '" . $id_session . "'";
 
    //open the table and print a header row, start with form as header
	echo "<form>";
    if ($result=mysql_query($sql)) {
      while ($row=mysql_fetch_array($result)) {
        echo "<input type=\"text\" value=\"".$row['qty']."\" id=\"item".$row['itemId']."\">";
		echo "".$row['itemName']." ";
        echo ' - ';
        echo "".$row['itemDesc']." ";
        echo "".$row['itemPrice']."<br>";
        //multiplay quantity and itemprice to get total of 1 product all together
        $totalCost += $row["qty"] * $row["itemPrice"];
      }
    }
    else {
      echo mysql_error();
    }
    echo "Total: ";
    //format of the totalcost 2 decimals and overall total
    echo number_format($totalCost, 2, ".", ",");
	echo '</form>';
}
?>